//
//  DYRiliView.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/3/11.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import SwiftDate

/// 日历
class DYRiliView: SYBaseView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    var compClosure:((String, String)->Void)?
    var collectionView: UICollectionView!
    var dates: [Date] = []
    // 选择的月份
    var selectMonthDate: Date! {
        didSet {
            titleLb.text = "\(selectMonthDate.sy_toString(format: "yyyy年MM月"))"
        }
    }
    // 选择的开始天
    var selectDayDate: Date! {
        didSet {
            showLb.text = "已选：\(selectDayDate.sy_toString(format: "MM月dd日"))"
            compAction()
        }
    }
    
    var bgView: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = UIColor.white
        v.layer.cornerRadius = 10.autoWidth()
        v.layer.masksToBounds = true
        return v
    }()
    
    var bgBt: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = UIColor(white: 0, alpha: 0.5)
        return v
    }()
    
    var compBt: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = Constant.blueColor
        v.layer.cornerRadius = 10.autoWidth()
        v.layer.masksToBounds = true
        v.setTitle("完成", for: .normal)
        v.setTitleColor(UIColor.white, for: .normal)
        v.titleLabel?.font = 18.autoBoldFontSize()
        return v
    }()
    
    
    var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 17.autoBoldFontSize()
        v.textColor = UIColor(hex: 0x1B1B1B)
        
        return v
    }()
    
    var showLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 14.autoFontSize()
        v.textColor = UIColor(hex: 0xFF5502)
        v.backgroundColor = UIColor(hex: 0xFFEEE5)
        v.textAlignment = .center
        return v
    }()
    
    var qianBt: UIButton = {
        let v: UIButton = UIButton()
        v.setImage(UIImage(named: "arrow_qian"), for: .normal)
        return v
    }()
    
    var houBt: UIButton = {
        let v: UIButton = UIButton()
        v.setImage(UIImage(named: "arrow"), for: .normal)
        return v
    }()
    
    var weekView: DYWeekView = DYWeekView()
    
    override func initViews() {
        self.isHidden = true
        bgBt.addAction {[weak self] in
            if let `self` = self {
                self.isHidden = true
            }
        }
        compBt.addAction {[weak self] in
            if let `self` = self {
                self.isHidden = true
//                self.compAction()
            }
        }
        qianBt.addAction {[weak self] in
            if let `self` = self {
                var date: String!
                if self.selectMonthDate.month == 1 {
                    date = "\(self.selectMonthDate.year-1)-\(12)-01"
                } else {
                    date = "\(self.selectMonthDate.year)-\(self.selectMonthDate.month-1)-01"
                }
                self.selectMonthDate = Date(date)!
                self.getMonth()
            }
        }
        houBt.addAction {[weak self] in
            if let `self` = self {
                var date: String!
                if self.selectMonthDate.month == 12 {
                    date = "\(self.selectMonthDate.year+1)-\(1)-01"
                } else {
                    date = "\(self.selectMonthDate.year)-\(self.selectMonthDate.month+1)-01"
                    
                }
                self.selectMonthDate = Date(date)!
                self.getMonth()
            }
        }
        
        self.backgroundColor = .clear
        addSubview(bgBt)
        addSubview(bgView)
        addSubview(compBt)
        bgView.addSubview(titleLb)
        bgView.addSubview(showLb)
        bgView.addSubview(qianBt)
        bgView.addSubview(houBt)
        bgView.addSubview(weekView)
        setCollectionView()
        
        bgView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(10.autoWidth())
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(466.autoWidth() + BOTTOM_SAFE_HEIGHT)
        }
        bgBt.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        qianBt.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(12.autoWidth())
            make.left.equalToSuperview().offset(1.autoWidth())
            make.height.equalTo(40.autoWidth())
            make.width.equalTo(40.autoWidth())
        }
        houBt.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(12.autoWidth())
            make.right.equalToSuperview().offset(-1.autoWidth())
            make.height.equalTo(40.autoWidth())
            make.width.equalTo(40.autoWidth())
        }
        weekView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(50.autoWidth())
            make.right.equalToSuperview()
            make.left.equalToSuperview()
            make.height.equalTo(30.autoWidth())
        }
        titleLb.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(20.autoWidth())
            make.centerX.equalToSuperview()
            make.height.equalTo(20.autoWidth())
        }
        showLb.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(341.autoWidth())
            make.left.right.equalToSuperview()
            make.height.equalTo(40.autoWidth())
        }
        compBt.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10.autoWidth() - BOTTOM_SAFE_HEIGHT)
            make.left.equalToSuperview().offset(15.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(44.autoWidth())
        }
        collectionView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(90.autoWidth())
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(251.autoWidth())
        }
        
        selectDayDate = Date("\(Date().year)-\(Date().month)-\(Date().day) \(dayLastTime)")!
        selectMonthDate = Date("\(Date().year)-\(Date().month)-\(Date().day)")!
        getMonth()
    }
    
    // 获取选择月份的天的数组
    func getMonth() {
        
        selectMonthDate = Date("\(selectMonthDate.year)-\(selectMonthDate.month)-01")!
        dates.removeAll()
        
        // 每月1号开始前的空白部分
        for _ in 1..<selectMonthDate!.weekday {
            dates.append(Date("1000-01")!)
        }
        
        for i in 0..<selectMonthDate!.monthDays {
            let riqi = "\(self.selectMonthDate.year)-\(self.selectMonthDate.month)-\(i + 1) \(dayLastTime)"
            dates.append(Date(riqi)!)
        }
        self.collectionView.reloadData()
    }
    
    func compAction() {
//        self.isHidden = true
        if self.isTodayOrTomorrow(selectDayDate).isEmpty {
            compClosure?(selectDayDate.sy_toString(format: "yyyy-MM-dd hh:mm:ss"), selectDayDate.sy_toString(format: "MM月dd日"))
        } else {
            compClosure?(selectDayDate.sy_toString(format: "yyyy-MM-dd hh:mm:ss"), self.isTodayOrTomorrow(selectDayDate))
        }
    }
    
    func setCollectionView() {
        
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: (SCREEN_WIDTH - 28) / 7, height: 41)
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 1
        layout.scrollDirection = .vertical
        
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DYRiliCell.self, forCellWithReuseIdentifier: NSStringFromClass(DYRiliCell.self))
        
        self.bgView.addSubview(self.collectionView)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dates.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell: DYRiliCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(DYRiliCell.self), for: indexPath) as? DYRiliCell
        
        let date = dates[indexPath.row]
        // 每月1号开始前的空白部分
        var day = ""
        if date.year != 1000 {
            day = "\(date.day)"
        }
        if selectDayDate == date {
            cell?.configCell("\(day)", true, date.isInPast)
        } else {
            cell?.configCell("\(day)", false, date.isInPast)
        }
        
        return cell!
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let date = dates[indexPath.row]
        if date.isInPast {
            return
        }
        selectDayDate = date
        self.collectionView.reloadData()
    }
}


class DYRiliCell: UICollectionViewCell {
    
    
    fileprivate var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 17.autoFontSize()
        v.textAlignment = .center
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configCell(_ title: String, _ isSelect: Bool? = false, _ isGuoqi: Bool? = false) {
        
        titleLb.text = title
        
        if isGuoqi == true {
            self.backgroundColor = .white
            titleLb.textColor = UIColor(hex: 0x999999)
        } else {
            if isSelect == true {
                self.backgroundColor = Constant.blueColor
                titleLb.textColor = .white
            } else {
                self.backgroundColor = .white
                titleLb.textColor = UIColor(hex: 0x1B1B1B)
            }
        }
        
    }
    
    fileprivate func initViews() {
        
        self.layer.cornerRadius = 4.autoWidth()
        self.layer.masksToBounds = true
        addSubview(titleLb)
        titleLb.snp.makeConstraints { (make) in
            
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalTo(13.0.autoWidth())
        }
    }
}


class DYWeekView: SYBaseView {
    
    override func initViews() {
        self.backgroundColor = UIColor(hex: 0xF0F6F3)
        for i in 0..<7 {
            let v = UILabel()
            v.font = 17.autoFontSize()
            v.textColor = UIColor(hex: 0x353535)
            v.text = weekDays[i]
            v.textAlignment = .center
            self.addSubview(v)
            let itemWidth = (SCREEN_WIDTH - 20) / 7
            v.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(10 + itemWidth*CGFloat(i))
                make.centerY.equalToSuperview()
                make.width.equalTo(itemWidth)
            }
        }
        
    }
}
